package com.service.iml;

import com.dao.UserMapper;
import com.domain.User;
import com.service.UserServiceInterface;
import com.utils.JwtTokenUtil;
import com.dto.HttpClientMapResult;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.net.HttpURLConnection;

@Service
public class UserService implements UserServiceInterface {

    @Resource
    private UserMapper userMapper;
    @Resource
    private JwtTokenUtil jwtTokenUtil;

    @Override
    public HttpClientMapResult login(String openid) {
        HttpClientMapResult result = null; //响应数据
        User user = userMapper.selectUserByOpenId(openid); //查询用户
        if (user == null) { //不存在此用户则需要先注册
            user = register(openid);
        }
        if (user != null) { //用户已注册
            result = new HttpClientMapResult();
            String token = jwtTokenUtil.generateToken(openid); //生成token
            result.setStatusCode(HttpURLConnection.HTTP_OK) //保存数据
                    .putToken(token)
                    .putParam("user", user);
        }
        return result;
    }

    @Override
    public User register(String openid) {
        User res = userMapper.selectUserByOpenId(openid);
        if (res == null && userMapper.insertUser(new User(openid))) res = userMapper.selectUserByOpenId(openid);
        return res;
    }

    @Override
    public User getUser(String openid) {
        return userMapper.selectUserByOpenId(openid);
    }

    @Override
    public Integer getUserId(String openid) {
        return userMapper.selectUserIdByOpenid(openid);
    }

    @Override
    public Boolean changeUserAvatar(Integer id, byte[] avatar) {
        return userMapper.updateUserAvatarById(id, avatar);
    }

    @Override
    public Boolean changeUserName(Integer id, String userName) {
        return userMapper.updateUserName(id, userName);
    }

}
